import env from "./env";
import xhr from "./xhr";
import plugins from "./plugins";

const mixin = {
    data: () => ({
        loading: false,
        env,
        xhr,
        plugins,
    }),
    computed: {
        profile() {
            return this.plugins.user.profile;
        },
    },
    methods: {
        async nextTick(handle, time) {
            if (time > 0) await new Promise((resolve) => setTimeout(resolve, time));
            return this.$nextTick(handle);
        },
        access(...keys) {
            let routes = this.$router.options.routes;
            let nodes = (() => {
                let role = this.profile ? this.profile.role : "";
                let isAdmin = this.profile ? this.profile.isAdmin : 0;
                // let isAdminT = this.profile ? this.profile.isAdminT : 0;
                
                if ( isAdmin> 0){
                    // console.log(isAdmin);
                    if (role === "holder" ) return ["/menu/work", "/menu/corp", "/menu/flow", "/menu/stats","/menu/org", "/menu/phone"];//联络员
                    if (role === "officer") return ["/menu/officer-work", "/menu/corp", "/menu/flow", "/menu/stats","/menu/inspect","/menu/joblife","/menu/policy","/menu/news","/menu/org", "/menu/phone"];//政府

                }

                if (role === "holder" ) return ["/menu/work", "/menu/corp", "/menu/flow", "/menu/stats", "/menu/phone"];//联络员
                if (role === "staff") return ["/menu/staff-work", "/menu/staff-corp", "/menu/flow", "/menu/phone"];//企业
                if (role === "officer") return ["/menu/officer-work", "/menu/corp", "/menu/flow", "/menu/stats","/menu/inspect","/menu/joblife","/menu/policy","/menu/news", "/menu/phone"];//政府
                //if (role === "officer") return ["/menu/work", "/menu/corp", "/menu/flow", "/menu/stats"];
                return [];
            })();
            // console.log(nodes);
            return keys.reduce((count, key) => {
                let route = routes.find((route) => route.name === key || route.path === key);
                let access = route ? this.access(...route.meta.nodes) : nodes.some((node) => node === key);
                return access ? count + 1 : count;
            }, 0) === keys.length;
        },
    },
    created() {
        this.removeRouterBeforeEach = this.$router.beforeEach((to, from, next) => next(!this.loading));
    },
    destroyed() {
        this.removeRouterBeforeEach();
    },
    beforeRouteEnter(to, from, next) {
        next((inst) => inst.$nextTick(function() {
            window.ss = this.env.debug ? this : null;
            document.title = this.$options.title + " - " + this.$root.$options.title;
            document.activeElement.blur();
            this.init();
        }));
    },
    beforeRouteUpdate(to, from, next) {
        this.destroy() ? next() + this.init() : next(false);
    },
    beforeRouteLeave(to, from, next) {
        this.destroy() ? next() : next(false);
    },
};

export default mixin;